package com.orhon.smartcampus.modules.baseinfo.fetcher;

import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.gqlModel.GQLPageParam;
import com.orhon.smartcampus.modules.base.mm.EnvArgsMapper;
import com.orhon.smartcampus.modules.baseinfo.dao.WeChatTemplateDao;
import com.orhon.smartcampus.modules.baseinfo.entity.WeChatTemplate;
import com.orhon.smartcampus.modules.baseinfo.gqlModel.GQLWeChatTemplate;
import com.orhon.smartcampus.modules.baseinfo.mm.WeChatTemplateMapper;
import com.orhon.smartcampus.modules.user.dao.TokenService;
import com.orhon.smartcampus.utils.ObjectToMap;
import com.orhon.smartcampus.utils.R;
import com.orhon.smartcampus.utils.Util;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 微信公众号消息推送模版列表
 */
@Component
public class WeChatTemplatesFetcher implements DataFetcher {

    @Autowired
    WeChatTemplateDao weChatTemplateDao;

    @Autowired
    TokenService tokenService;

    @Override
    public Object get(DataFetchingEnvironment env) throws Exception {

        String token = tokenService.getSystemToken();
        if(token==null) {
            return  R.NoLogin();
        }

        List<GQLWeChatTemplate> gqlWeChatTemplates = new ArrayList<GQLWeChatTemplate>();
        GQLPageParam pageParam = EnvArgsMapper.MAPPER.fromArgs(env);
        String hql = "from WeChatTemplate as wt ";

        if(env.containsArgument("condition")) {
            HashMap<String,Object> map = ObjectToMap.to(env.getArgument("condition"));
            if(map.get("templateTitle")!=null) {
                hql += "and wt.templateTitle" + Util.decide(map.get("templateTitle"));
            }
        }

        List<WeChatTemplate> list = weChatTemplateDao.find(hql , null ,pageParam.getPage() , pageParam.getLimit());

        for (WeChatTemplate weChatTemplate : list) {
            GQLWeChatTemplate gqlWeChatTemplate = WeChatTemplateMapper.MAPPER.toWeChatTemplate(weChatTemplate);
            gqlWeChatTemplates.add(gqlWeChatTemplate);
        }

        Long total = 0L;
        if (env.getSelectionSet().contains("total")){
            total = weChatTemplateDao.getTotalCount(hql);
        }
        return Result.ok().put("data", gqlWeChatTemplates).put("total", total);
    }

}
